﻿using Canteen.Core.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
using StackExchange.Redis;
using System;


namespace Canteen.Core.Common
{
    public static class DbSetup
    {
        public static void AddDbSetup(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddDbContextPool<CanteenDbContext>(options =>
                options.UseSqlServer(configuration.GetConnectionString("CanteenMSSQL"))
            );

            //redis缓存
            services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.TryAddSingleton<ObjectPool<RedisCache>>(serviceProvider =>
            {
                var provider = serviceProvider.GetRequiredService<ObjectPoolProvider>();
                var options = ConfigurationOptions.Parse(configuration.GetConnectionString("Redis"), true);
                return provider.Create(new RedisCachePooledObjectPolicy(options));
            });
            services.TryAddSingleton<IRedisCacheManager, RedisCacheManager>();
        }
    }
}
